package com.unknowpupil.sell.controller;

import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.model.RefundRequest;
import com.lly835.bestpay.model.RefundResponse;
import com.unknowpupil.sell.common.enums.ErrorCodeEnum;
import com.unknowpupil.sell.common.request.Result;
import com.unknowpupil.sell.dto.OrderDTO;
import com.unknowpupil.sell.exception.SellException;
import com.unknowpupil.sell.service.IOrderMasterService;
import com.unknowpupil.sell.service.PayServer;
import com.unknowpupil.sell.utils.MathUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;

/**
 * @Classname: PayController
 * @Author: <a> w10g </a>
 * @CreateDate: Create in 2020/1/1 16:24
 * @Description:
 * @Version: 1.0
 */

@Api(tags = {"PayController"}, description = "支付模块")
@Controller
@RequestMapping("/api/pay/")
@Slf4j
public class PayController {
    @Autowired
    private IOrderMasterService orderMasterService;
    @Autowired
    private PayServer payServer;

    @GetMapping("create")
    public ModelAndView create(@RequestParam("orderId") String orderId, @RequestParam("returnUrl") String returnUrl) {
        ModelAndView modelAndView = new ModelAndView();
        OrderDTO orderDTO = orderMasterService.finOne(orderId);
        if (orderDTO == null) {
            throw new SellException(ErrorCodeEnum.ORDER_NOT_EXIST);
        }
        //发起支付
        PayResponse payResponse = payServer.create(orderDTO);
        modelAndView.setViewName("pay/create");
        modelAndView.addObject("returnUrl", returnUrl);
        modelAndView.addObject("payResponse", payResponse);
        return modelAndView;


    }

    /**
     * 异步通知会不断通知我们
     *
     * @param notifyData
     */
    @PostMapping("/callback")
    @ResponseBody
    public ModelAndView callback(@RequestBody String notifyData) {
        //微信支付异步通知
        PayResponse response = payServer.callBack(notifyData);
        //告诉微信
        return new ModelAndView("pay/success");


    }
    /**
     * 功能描述: <br>
     * 〈退款〉
     *
     * @param: orderDTO
     * @since: 1.0.0
     * @auther: w10g
     * @return:
     * @Date: 2020/1/2 16:54
     */
    @PostMapping("/refound")
    public void refound(OrderDTO orderDTO){
        RefundResponse refundRequest= payServer.refound(orderDTO);
    }
}
